package com.gift.controller;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class Controller {
	
	@Value("${server.port}")
    private int port;
	
	@GetMapping("/getPort")
	public String getPort() {
		return port +"";
	}
	
	
	
	@PostMapping("/test")
	public String test(HttpServletRequest request) throws IOException {
		String requestString = getRequestJson(request);
		System.out.println("gift~~~~~");
		return "ok";
	}

	private String getRequestJson(ServletRequest request) throws IOException {
		InputStream in = request.getInputStream();
		int length = 0;
		ByteArrayOutputStream bos = null;
		DataOutputStream output = null;
		try {
			bos = new ByteArrayOutputStream();
			output = new DataOutputStream(bos);
			byte[] data = new byte[4096];
			// int totalLen = 0;
			while ((length = in.read(data, 0, data.length)) != -1) {
				output.write(data, 0, length);
				// totalLen +=length;
			}
			byte[] bytes = bos.toByteArray();
			String text = new String(bytes, "UTF-8");
			return text;
		} finally {
			if (output != null) {
				output.close();
			}
		}
	}
}
